package com.example.demo.leetcode.zuocheng.btree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author xujm
 * @version V2.4
 * @since 2.4.0 2021/8/29 10:46
 */
public class Tree_二叉树的序列化和反序列化 {


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    //先序遍历的序列化
    public static Queue first_serialization(TreeNode root){

        Queue<Integer> queue = new LinkedList<>();
        first_process(root,queue);
        return queue;
    }

    public static void first_process(TreeNode root,Queue<Integer> queue){

        if(root == null){
            queue.add(null);
            return;
        }
        queue.add(root.val);
        first_process(root.left,queue);
        first_process(root.right,queue);
    }


    //先序遍历的反序列化,也是先左再右
    public static TreeNode first_reseriallization(Queue<Integer> queue){
        Object poll = queue.poll();
        if(poll == null){
            return null;
        }
        TreeNode node = new TreeNode((Integer) poll);
        node.left = first_reseriallization(queue);
        node.right = first_reseriallization(queue);
        return node;
    }

    public static void main(String[] args) {

        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode7 = new TreeNode(7);
        treeNode1.left=treeNode2;treeNode1.right=treeNode3;
        treeNode2.left=treeNode4;treeNode2.right=treeNode5;
        treeNode3.left=treeNode6;treeNode3.right=treeNode7;

        Queue queue = first_serialization(treeNode1);
        TreeNode treeNodex = first_reseriallization(queue);
        System.out.println(true);

    }



    //按层序列化






}
